<template>
  <div class="editor-container">
    <Toolbar class="editor-toolbar" :editor="editorRef" />
    <Editor 
      class="editor-content"
      v-model="props.modelValue" 
      @onCreated="handleCreated"  
      @onChange="handleChange"
    />
  </div>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css'
import { shallowRef, onMounted, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { uploadApi } from '../api'

// 编辑器实例
const editorRef = shallowRef()

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:modelValue'])

// 配置上传处理器
const configureUploader = (editor: any) => {
  const uploadConfig = {
    async customUpload(file: File, insertFn: any) {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        uploadApi.upload.call({
          name: file.name,
          base64: reader.result
        }).then((res: any) => {
          insertFn(res, '', '')
        })
      }
    }
  }

  editor.getConfig().MENU_CONF['uploadImage'] = uploadConfig
  editor.getConfig().MENU_CONF['uploadVideo'] = uploadConfig
}

const handleCreated = (editor: any) => {
  editorRef.value = editor
  configureUploader(editor)
}

// 监听 modelValue 变化
watch(() => props.modelValue, (newValue) => {
  if (editorRef.value) {
    editorRef.value.setHtml(newValue)
  }
})

const handleChange = (editor: any) => {
  emit('update:modelValue', editor.getHtml())
}
</script>

<style scoped>
.editor-container {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.editor-toolbar {
  border-bottom: 1px solid #e4e7ed;
  background: #fff;
}

.editor-content {
  height: 300px;
  overflow-y: auto;
  background: #fff;
}
</style>